import fcgi.Thread;
import fcgi.Connection;
import fcgi.Request;

import tango.io.stream.Format, tango.core.Memory, tango.time.Clock;

public int run (FastCGIRequest request)
{
        static int counter = 0;
	ubyte[1024*16] tmp;
        auto stdout = new vBuffer(tmp);
	scope(exit){
		request.stdout.write(stdout.slice);
	}

        stdout ("Content-type: text/html\r\n\r\n") ("<head><title>My first page</title></head>");
        stdout ("<body>");

        // some counters
        synchronized
                counter++;
	
	auto now = Clock.now ;
        stdout ("<h1> Hello world </h1><br>") ("Request #") (counter) ("<br><br>\n");

        // Write IP
        auto ip = ("REMOTE_ADDR" in request.args);
        if (ip)
        {
                stdout ("Your IP is ") (*ip) ("<br><br>\n");
        }
        else
        {
                stdout ("Cannot extract IP :(<br><br>\n");
        }

        // Write stdin
        stdout ("Data: \"");
        while (1)
        {
                char[10] string;
                int rd = request.stdin.read (string);
                if (rd > 0)
                        stdout (string [0 .. rd]);
                if (rd != string.length)
                {
                        stdout ("\"<br><br>");
                        break;
                }
        }

        // Write all arguments
        stdout ("\nYour environment:<br>\n") ;
        foreach (key, value; request.args)
        {
               stdout ("request.args[\"") (key) ("\"] = \"") (value) ("\"<br>\n");
        }
	stdout("<br />")( (Clock.now-now).millis )("ms");
        stdout ("</body>\n");

        return 0;
}

int main (char[][] args)
{
        FastCGIConnection connection = new FastCGIConnection ("", "1983");
	GC.disable;
        return FastCGIThread.loop (connection, &run, true, 10);
}
